﻿using Minecraft.Config;
using Minecraft.Config.Csv.CsvCls;
using Minecraft.Config.Csv.CsvCom;
using Minecraft.Model;
using Minecraft.Model.Dropinfo;
using Minecraft.Model.ReqResp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Minecraft.ServerHall
{
	public static class DropinfoExt
	{
		/// <summary>
		/// 获取新的dropId
		/// </summary>
		/// <param name="session"></param>
		/// <returns></returns>
		public static int GetNewDropInfoId(this MinecraftSession session)
		{
			if (!session.minecraftSessionInfo.dropinfoList.Any())
			{
				return 1;
			}
			var maxId = session.minecraftSessionInfo.dropinfoList.Max(m => m.DropId);
			return (maxId + 1);
		}
		///// <summary>
		///// 针对 DropItemIdAndNum 字段转换成掉落的物品信息列表
		///// </summary>
		///// <param name="dropinfo"></param>
		///// <returns></returns>
		//public static List<DropinfoDropResourceInfo> GetDropinfoGoodsInfoList_Convert(this DropinfoModel dropinfo)
		//{
		//	List<DropinfoDropResourceInfo> dropinfoDropResourceInfoList = new List<DropinfoDropResourceInfo>();
		//	//var itemidsAndNumsStrs = dropinfo.DropItemIdAndNum.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
		//	//foreach (var itemidsAndNumsStr in itemidsAndNumsStrs)
		//	//{
		//	//	var idsAndNums = itemidsAndNumsStr.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
		//	//	DropinfoDropResourceInfo dropinfoDropResourceInfo = new DropinfoDropResourceInfo
		//	//	{
		//	//		GoodsItemId = idsAndNums[0],
		//	//		Num = int.Parse(idsAndNums[1])
		//	//	};
		//	//	dropinfoDropResourceInfoList.Add(dropinfoDropResourceInfo);
		//	//}
		//	return dropinfoDropResourceInfoList;
		//}

		///// <summary>
		///// 针对 DropItemIdAndNum 字段的修改要从对象列表转换成字符串
		///// </summary>
		///// <param name="dropinfo"></param>
		///// <param name="dropinfoDropResourceInfo"></param>
		//public static void TransformToDropItemIdAndNum_Convert(this DropinfoModel dropinfo,
		//	DropinfoDropResourceInfo dropinfoDropResourceInfo)
		//{
		//	//var list = dropinfo.GetDropinfoGoodsInfoList_Convert();
		//	//var index = list.FindIndex(m => m.GoodsItemId == dropinfoDropResourceInfo.GoodsItemId);
		//	//if (index >= 0)
		//	//{
		//	//	list.RemoveAt(index);
		//	//}
		//	//if (dropinfoDropResourceInfo.Num > 0)
		//	//{
		//	//	list.Add(dropinfoDropResourceInfo);
		//	//}
		//	//dropinfo.DropItemIdAndNum = string.Join("|", list.ToList().ConvertAll(info =>
		//	//{
		//	//	return string.Join("#", info.GoodsItemId, info.Num);
		//	//}).ToArray());
		//}
		/// <summary>
		/// 得到除去家具类型的图纸资源类型id列表（drop资源采集相关）
		/// </summary>
		/// <returns></returns>
		public static List<int> GetDrawingResourceTypeIdList(this MinecraftSession session)
		{
			var enumFurnitureTypeList = EnumFurnitureType.Unknown.GetEnumDesxriptionDict().Select(m => (EnumFurnitureType)m.Key).ToList();
			enumFurnitureTypeList.Remove(EnumFurnitureType.Unknown);
			var furnitureTypeIdList = enumFurnitureTypeList.Select(m => (int)m).ToList();
			var typeList = CsvConfig.GetdrawingDict().Select(m => m.Value.Type_Convert).Distinct().ToList();
			var li = typeList.Except(furnitureTypeIdList).ToList();
			return li;
		}

		/// <summary>
		/// 随机获取掉落物品信息
		/// </summary>
		/// <param name="session"></param>
		/// <returns></returns>
		public static List<DropinfoDropResourceInfo> GetDropinfoDropRandomResourceInfoList(this MinecraftSession session, string dropId)
		{
			var dropInfo = CsvConfig.GetMod_DropInfoById(dropId);

			Random random = new Random(DateTimeHelper.GetTotalSecondsIntOfThisYear());
			List<ModDropItemInfo> modDropItemInfoList = dropInfo.GetModDropItemInfoList_Convert();
			List<ModDropRuleInfo> modDropRuleInfoList = modDropItemInfoList.GetModDropRuleInfoList();
			var dropCount = random.Next(1, dropInfo.drop_max_Convert + 1);
			List<DropinfoDropResourceInfo> dropinfoDropResourceInfoList = new List<DropinfoDropResourceInfo>();
			//foreach (var modDropItemInfo in modDropItemInfoList)
			//{
			//	if (rateInt <= modDropItemInfo.dropRate)
			//	{
			//		//在生成几率内，生成对应物品个数
			//		var goodsCount = random.Next(modDropItemInfo.minCount, modDropItemInfo.maxCount + 1);
			//		dropinfoDropResourceInfoList.Add(new DropinfoDropResourceInfo
			//		{
			//			GoodsItemId = modDropItemInfo.itemId,
			//			Num = goodsCount,
			//		});
			//	}
			//}
			for (int i = 0; i < dropCount; i++)
			{
				var rateInt = random.Next(1, modDropRuleInfoList.Max(m => m.maxRandom));
				var modDropItemInfo = modDropRuleInfoList.FirstOrDefault(m => rateInt >= m.minRandom && rateInt <= m.maxRandom);
				if (modDropItemInfo == null)
				{
					throw new Exception("掉落规则生成有问题，请和服务器沟通");
				}
				var goodsCount = random.Next(modDropItemInfo.modDropItemInfo.minCount, modDropItemInfo.modDropItemInfo.maxCount + 1);
				dropinfoDropResourceInfoList.Add(new DropinfoDropResourceInfo
				{
					GoodsItemId = modDropItemInfo.modDropItemInfo.itemId,
					Num = goodsCount,
				});
			}
			return dropinfoDropResourceInfoList;
		}
		/// <summary>
		/// 生成掉落规则
		/// </summary>
		/// <param name="modDropItemInfoList"></param>
		/// <returns></returns>
		public static List<ModDropRuleInfo> GetModDropRuleInfoList(this List<ModDropItemInfo> modDropItemInfoList)
		{
			List<ModDropRuleInfo> modDropRuleInfoList = new List<ModDropRuleInfo>();
			for (int i = 0; i < modDropItemInfoList.Count(); i++)
			{
				int minRandom = 0;
				int maxRandom = 0;
				List<ModDropItemInfo> takeModDropItemInfoList = new List<ModDropItemInfo>();
				if (i <= 0)
				{
					minRandom = 1;
					maxRandom = modDropItemInfoList[i].dropRate;
				}
				else
				{
					minRandom = modDropRuleInfoList.Take(i).Max(m => m.maxRandom) + 1;
					maxRandom = modDropRuleInfoList.Take(i).Max(m => m.maxRandom) + modDropItemInfoList[i].dropRate;
				}
				ModDropRuleInfo modDropRuleInfo = new ModDropRuleInfo
				{
					modDropItemInfo = modDropItemInfoList[i],
					minRandom = minRandom,
					maxRandom = maxRandom
				};
				modDropRuleInfoList.Add(modDropRuleInfo);
			}
			return modDropRuleInfoList;
		}
		/// <summary>
		/// 清除指定地图的掉落物品信息
		/// </summary>
		public static void ClearMapDropGoodsInfo(this MinecraftSession session, string mapId)
		{
			session.minecraftSessionInfo.dropinfoList.RemoveAll(m => m.MapId == mapId);
			session.minecraftSessionInfo.goodsList.RemoveAll(m =>
				m.enumGoodsBelongsToType_Convert == EnumGoodsBelongsToType.MonsterCorpseAndDismantleFurniture);
		}

		/// <summary>
		/// 掉落加经验
		/// </summary>
		/// <param name="session"></param>
		public static BaseResp DropAddExp(this MinecraftSession session,
			List<DropinfoDropResourceInfo> dropinfoDropResourceInfoList,
			List<KeyValueEnumAttributeInt> dropAttributeList,
			List<KeyValueEnumAttributeInt> attributeList)
		{
			//经验特殊处理，直接加到玩家属性上
			var expDropResourceInfo = dropinfoDropResourceInfoList.FirstOrDefault(m => m.GoodsItemId == MinecraftConfig.ExperienceItemId);
			if (expDropResourceInfo != null)
			{
				var expItemInfo = CsvConfig.GetMod_ItemsInfoById(expDropResourceInfo.GoodsItemId);
				if (expItemInfo == null)
				{
					return new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：物品表中 expItemInfo id为【{expDropResourceInfo.GoodsItemId}】 经验信息为空）" };
				}
				var behaviorInfo = CsvConfig.GetMod_BehaviorInfoById(expItemInfo.Behavior_id);
				if (behaviorInfo == null)
				{
					return new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：行为表中 behaviorInfo id为 【{expItemInfo.Behavior_id}】 信息为空）" };
				}
				Match match = Regex.Match(behaviorInfo.Behavior, @"AlterAttribute\((\d+)#(\d+)\)");
				if (!match.Success)
				{
					return new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：行为表中 behaviorInfo id为 【{expItemInfo.Behavior_id}】正则匹配不成功）" };
				}
				EnumAttribute enumAttribute = (EnumAttribute)int.Parse(match.Groups[1].Value);
				int expValue = int.Parse(match.Groups[2].Value);
				if (enumAttribute != EnumAttribute.CurExp)
				{
					return new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：行为表中 behaviorInfo id为 【{expItemInfo.Behavior_id}】正则匹配 的第一个 group值 为 【{match.Groups[1].Value}】，并不是【{EnumAttribute.CurExp.ToString()}】）" };
				}
				//直接加经验
				int dropExp = expDropResourceInfo.Num * expValue;
				session.minecraftSessionInfo.player.Exp += dropExp;
				dropinfoDropResourceInfoList.RemoveAll(m => m.GoodsItemId == expDropResourceInfo.GoodsItemId);

				dropAttributeList.Add(new KeyValueEnumAttributeInt { key = EnumAttribute.CurExp, value = dropExp });
				attributeList.Add(new KeyValueEnumAttributeInt { key = EnumAttribute.CurExp, value = session.minecraftSessionInfo.player.Exp });

				session.ExperienceChange();
			}
			return new BaseResp();
		}
	}
}
